package co.edu.unal.franquicias.visa.auth;

import com.sun.jersey.api.NotFoundException;
import com.sun.jersey.api.view.Viewable;
import com.sun.jersey.oauth.server.api.providers.DefaultOAuthProvider;
import com.sun.jersey.oauth.signature.OAuthParameters;
import java.net.URI;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

@Path("/authorize")
public class AuthorizationResource extends ResourceBase {
    private @Context DefaultOAuthProvider provider;

    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable getHtml(@QueryParam("oauth_token") String token) {
        return new Viewable("/authorize", provider.getRequestToken(token));
    }

    @POST
    public Response post(@FormParam("approve") boolean approved, @FormParam("token") String token) {
        // only allow if the user has write access
        checkWrite();
        DefaultOAuthProvider.Token t = provider.getRequestToken(token);
        if (t == null) {
            throw new NotFoundException();
        }

        String verifier = "";
        if (approved) {
            verifier = provider.authorizeToken(t, security.getUserPrincipal(), null);
        }

        String callback = t.getCallbackUrl();
        if (callback == null || callback.equalsIgnoreCase("oob")) {
            // return a plain text response with the verifier
            return
Response.ok("Switch back to your application and enter this verification code: " + verifier).type(MediaType.TEXT_PLAIN).build();
        } else {
            // redirect to the callback URL providing the token and verifier in the params.
            URI uri = UriBuilder.fromUri(t.getCallbackUrl())
                    .queryParam(OAuthParameters.TOKEN, token)
                    .queryParam(OAuthParameters.VERIFIER, verifier).build();
            return Response.seeOther(uri).build();
        }
    }
}
